<template>
	<view>
		<view class="u-demo-block__content" style="margin: 16rpx;">
			<view class="u-page__tag-item">
				<u-search placeholder="输入合同号、工单" 
					v-model="queryKey" 
					@custom="queryPickingByQueryKey"
					@search="queryPickingByQueryKey"></u-search>
			</view>
		</view>
		<view>
			<u-tabs
				@click="tabClick"
				:list="list1"
				lineWidth="60"
				lineColor="#f56c6c"
				:activeStyle="{
					color: '#303133',
					fontWeight: 'bold',
					transform: 'scale(1.05)'
				}"
				:inactiveStyle="{
					color: '#606266',
					transform: 'scale(1)'
				}"
				itemStyle="padding-left: 15px; padding-right: 15px; height: 34px;">
				<view
					slot="right"
					style="padding-left: 10px;"
					@tap="advanceClick">
					<u-icon
							name="list-dot"
							size="30"
							bold>
					</u-icon>
				</view>
			</u-tabs>
		</view>
		<view class="card-container">
			<view v-for="(work, index) in this.orderList"
			class="card-wrap"
			:class="{ 'card-wrap-selected': work.selectedCard === 1 }"
			@click="selectCard(work)">
				<view class="card-item">
					订单合同：
					<u--text :text="work.contractCode" type="info"></u--text>
					<!-- <u-tooltip :text="work.contractCode" bgColor="#e3e4e6"></u-tooltip> -->
				</view>
				<view class="card-item">
					产地：
					<u--text :text="sliceFName(work.factoryName)" type="info"></u--text>
					班组：
					<u--text :text="work.teamName" bgColor="#e3e4e6"></u--text>
				</view>
				<view class="card-item">
					生产订单：
					<u--text :text="work.orderCode" type="info"></u--text>
					<!-- <u-tooltip :text="work.orderCode" bgColor="#e3e4e6"></u-tooltip> -->
				</view>
				<view class="card-item">
					业务状态：
					<u--text :text="work.minKingStatusDesc" type="error" v-if="work.minKingStatus==1 || work.minKingStatus==2"></u--text>
					<u--text :text="work.minKingStatusDesc" type="success" v-else-if="work.minKingStatus==6 || work.minKingStatus==7"></u--text>
					<u--text :text="work.minKingStatusDesc" type="primary" v-else></u--text>
					领料状态：
					<u--text :text="work.minKingPickStatusDesc" type="info"></u--text>
				</view>
				<view class="card-item">
					产品规格(首行)：
					<u--text :text="work.bomName" type="warning"></u--text>
					<u--text :text="work.bomStandard" type="warning"></u--text>
				</view>
				<view class="card-item">
					订单日期：
					<u--text :text="work.order_date" type="info"></u--text>
					生产数量：
					<u--text :text="work.sumPlanNum" bgColor="#e3e4e6"></u--text>
				</view>
				
				<view class="card-item" v-if="selectedIndex == 0">
					<u-button text="查看订单产品明细" size="normal" type="warning" style="margin-right: 2px;" @click="queryProductInfoByContract(work)"></u-button>
					<u-button text="一键批量领料" size="normal" type="primary" @click="toPicking(work)" v-if="work.auditStatus==='YES'&&orderType==='1'"></u-button>
					<u-button text="一键批量补料" size="normal" type="primary" @click="toFeedMtrl(work)" v-else-if="work.auditStatus==='YES'&&orderType==='6'"></u-button>
					<u-button text="一键批量退料" size="normal" type="primary" @click="toReturnMtrl(work)" v-else-if="work.auditStatus==='YES'&&orderType==='7'"></u-button>
					<u-button text="金蝶未审核" size="normal" type="error" v-else></u-button>
				</view>
				<view class="card-item" v-else>
					<u-button text="查看订单产品明细" size="normal" type="warning" style="margin-right: 2px;" @click="queryProductInfoByContract(work)"></u-button>
					<u-button text="一键批量补料" size="normal" type="primary" v-if="orderType==='6'" @click="toFeedMtrl(work)"></u-button>
					<u-button text="一键批量退料" size="normal" type="primary" v-else-if="orderType==='7'" @click="toReturnMtrl(work)"></u-button>
					<u-button text="查看领料详情" size="normal" type="primary" v-else @click="toDetail(work)"></u-button>
				</view>
			</view>
		</view>
		<view v-if="this.orderList.length == 0" style="padding-top: 60px;">
			<u-loading-icon text="数据加载中" textSize="18" color="#19be6b" :show="loadingShow"></u-loading-icon>
			<u-empty mode="data" v-if="!loadingShow"></u-empty>
		</view>
		
		<u-loadmore :status="status" />
		<!-- 点击选择产品 ，弹出产品类型选框 -->
		<u-popup
			:safeAreaInsetBottom="true"
			:safeAreaInsetTop="true"
			:mode="popupData.mode"
			:show="show"
			:round="popupData.round"
			:overlay="popupData.overlay"
			:borderRadius="popupData.borderRadius"
			:closeable="popupData.closeable"
			:closeOnClickOverlay="popupData.closeOnClickOverlay"
			@close="close"
			@open="open"
			customStyle="max-height: 100vh; overflow-y: auto; overflow-x: hidden;">
			<view
				class="u-popup-slot"
				:style="{
					width: '240px',
					marginTop: '25rpx',
				}">
				 <view style="margin-left: 5px;"><u--text text="选择产品:" type="info"></u--text></view>
				 <u-line></u-line>
				 <u-row customStyle="margin-bottom: 4px;margin-top: 4px;" v-for="(group, groupIndex) in groupedProductList" 
					:key="groupIndex">
					<u-col span="6" v-for="(product, productIndex) in group" :key="product.productId">
						<u-tag :text="`${product.productName}`" 
						:plain="!product.checked" 
						type="warning" 
						:name="`${product.productId}`" 
						style="margin: 5px; white-space: normal; word-wrap: break-word;"
						@click="productSelected"></u-tag>
					</u-col>
					<!-- <u-col span="6">
						<u-tag :text="`选项1`" :plain="false" type="warning" :name="1" style="margin: 5px;"></u-tag>
					</u-col> -->
				</u-row>
				<u-row customStyle="margin-bottom: 4px; margin-top: 30px;" gutter="6" >
					<u-col span="6">						
						<u-button type="primary" @click="productConfirm" style="margin: 5px;">确认</u-button>
					</u-col>
					<u-col span="6">
						<!-- <u-tag :text="`选项1`" :plain="false" type="warning" :name="1" style="margin: 5px;"></u-tag> -->
						<u-button type="warning" @click="reset" style="margin-right: 5px;">重置</u-button>
					</u-col>
				</u-row>
				<!-- <u-row customStyle="margin-bottom: 4px">
					<u-col span="6">
						<u-tag :text="`选项2`" :plain="true" type="warning" :name="1" style="margin: 5px;"></u-tag>
					</u-col>
					<u-col span="6">
						<u-tag :text="`选项3`" :plain="false" type="warning" :name="1" style="margin: 5px;"></u-tag>
					</u-col>
				</u-row> -->
				<!-- Floating buttons -->
				<!-- <view 
				  style="position: fixed; bottom: 0; left: 50%; transform: translateX(-50%); width: 240px; background-color: white; box-shadow: 0 -2px 10px rgba(0,0,0,0.1);"
				>
				  <view style="display: flex; justify-content: space-between; padding: 10px;">
					<u-button type="default">取消</u-button>
					<u-button type="primary">确认</u-button>
				  </view>
				</view> -->
			</view>
		</u-popup>
		
		<u-popup :show="productShow" mode="top"  @close="productClose" :closeOnClickOverlay="false">
			<view >
				<view class="card-wrap">
					<view class="card-item">
						订单合同：<u-tooltip :text="selectedContractCode" bgColor="#e3e4e6"></u-tooltip>
					</view>
					<!-- 产品列表（主表） -->
					<view style="margin-top: 0px; max-height: 70vh; overflow-y: auto;">
						<uni-table ref="tableOfProduct" :loading="detailLoading"
							border
							stripe 
							type="" 
							emptyText="暂无更多数据">
						<uni-tr style="background-color: #dbfbdb;">
							<uni-th align="left" width="5" style="font-size: 12px;color: #62c188;">序号</uni-th>
							<uni-th align="left" width="40" style="font-size: 12px;color: #62c188;">产品编码</uni-th>
							<uni-th align="left" width="60" style="font-size: 12px;color: #62c188;">物料编码</uni-th>
							<uni-th align="left" width="80" style="font-size: 12px;color: #62c188;">物料名称</uni-th>
							<uni-th align="left" width="80" style="font-size: 12px;color: #62c188;">物料规格</uni-th>
							<uni-th align="left" width="80" style="font-size: 12px;color: #62c188;">业务状态</uni-th>
							<uni-th align="left" width="60" style="font-size: 12px;color: #62c188;">生产数量</uni-th>
							<uni-th align="left" style="font-size: 12px;color: #62c188;">已齐套数量</uni-th>
						</uni-tr>
						<uni-tr v-for="(item, index) in workOrderList" :key="index">
							<uni-td align="left" style="font-size: 12px;text-align: left;">{{ index+1 }}</uni-td>
							<uni-td align="left" style="font-size: 12px;text-align: left;">{{ item.productCode }}</uni-td>
							<uni-td align="left" style="font-size: 12px;text-align: left;">{{ item.bomCode }}</uni-td>
							<uni-td align="left" style="font-size: 12px;text-align: left;">{{ item.bomName }}</uni-td>
							<uni-td align="left" style="font-size: 12px;text-align: left;">{{ item.bomStandard }}</uni-td>
							<uni-td align="left" style="font-size: 12px;text-align: left;">{{ item.kingStatusDesc }}</uni-td>
							<uni-td align="left" style="font-size: 12px;text-align: left;">{{ item.maxPickingNum }}</uni-td>
							<uni-td align="left" style="font-size: 12px;text-align: left;">{{ item.finishQty }}</uni-td>
						</uni-tr>
						</uni-table>
					</view>
				</view>
			</view>
			<u-button
				type="primary"
				text="关闭"
				shape="circle" 
				customStyle="width: 240rpx;"
				@click="productShow = !productShow"
			></u-button>
		</u-popup>
	</view>
</template>

<script>
	
import FloatScanButton from '@/components/button/FloatScanButton'
import * as workorderApi from '@/api/order/workorder';
export default {
	components: {
		FloatScanButton,
	},
	data() {
		return {
			status: 'loadmore',
			pageNum: 1,
			totalPageCount: 0,
			
			orderList: [],
			
			list1: [{
				name: '等待领料',
			}, {
				name: '全已领料',
			}],
			selectedIndex: 0,
			loadingShow: false,
			productList: [],
			groupedProductList: [],
			popupData: {
				overlay: true,
				mode: 'right',
				closeOnClickOverlay: true
			},
			show: false,
			// 查询参数
			queryKey: "",
			productName: null,
			value: "",
			checked: ["选中"],
			selectedCard: null, // 选中的卡片ID
			trueValue: true,
			
			detailLoading: false,
			selectedContractCode: null,
			productShow: false,
			workOrderList: [],
			orderType: "1",
		}
	},
	mounted() {
		// 初始化列表数据
		this.orderList = [];
		this.queryProductName();
		this.queryPickingList();
	},
	onLoad(options) {
		if (options.orderType) {
			this.orderType = options.orderType;
		}
	},
	methods: {
		sliceFName(factoryName) {
			return factoryName ? factoryName.slice(0,2) : '-';
		},
		onReachBottom() {
			console.log("onReachBottom", this.pageNum, this.totalPageCount);
			if (this.pageNum > this.totalPageCount) {
				console.log("已经加载到最多了");
				return;
			}
			this.pageNum ++;
			this.queryPickingList();
		},
		productClose(){
			this.productShow = false;
		},
		queryProductInfoByContract(row) {
			this.detailLoading = true;
			this.selectedContractCode = row.contractCode;
			this.workOrderList = [];
			workorderApi.queryPickingListInfoByContractCode({
				pageNum: 1, 
				pageSize: 60, 
				factoryId: row.factoryId,
				teamId: row.teamId,
				orderCode: row.orderCode,
				contractCode: row.contractCode,
			}).then(res => {
				if (res && res.data) {
					this.workOrderList = res.data.noMergeList || [];
				}
				this.detailLoading = false;
				this.productShow = true;
			}).catch(err => {
				// 提交异常
				console.error("商品规格明细查询发生异常", err);
				this.workOrderList = [];
				this.detailLoading = false;
			});
		},
		queryProductName() {
			workorderApi.queryProductNameList({
				pageNum: 1, pageSize: 2000, 
			}).then(res => {
				// console.log("领料列表查询:", res);
				if (res && res.data) {
					let result = res.data || [];
					let index = 0;
					this.productList = [];
					for (const item of result) {
						item.productId = ++index;
						item.checked = false;
						this.productList.push(item);
					}
				}
			});
		},
		queryPickingByQueryKey() {
			this.resetParams();
			this.queryPickingList();
		},
		resetParams() {
			this.pageNum = 1;
			this.totalPageCount = 0;
			this.orderList = [];
		},
		queryPickingList() {
			console.log("selectedIndex:",this.selectedIndex);
			workorderApi.queryPickingList({
				pageNum: this.pageNum,
				queryKey: this.queryKey,
				productName: this.productName,
				isFinished: this.selectedIndex === 1 ? true : false,
			}).then(res => {
				// console.log("领料列表查询:", res);
				if (res && res.rows) {
					const result = res.rows || [];
					for (let item of result) {
						this.orderList.push(item);
					}
					this.totalPageCount = res.totalPageCount || 0;
					if (this.pageNum >= this.totalPageCount) {
						this.status = 'nomore';
					} else {
						this.status = 'loading';
					}
				}
			});
		},
		groupedProducts() {
			const size = 2;
		      return this.productList.reduce((result, item, index) => {
		        const chunkIndex = Math.floor(index / size);
		        if (!result[chunkIndex]) {
		          result[chunkIndex] = [];
		        }
		        result[chunkIndex].push(item);
		        return result;
		      }, []);
		},
		productSelected(name){
			const found = this.productList.find(item => item.productId === Number(name));
			console.log("click", name, found);
			if (found) {
				found.checked = !found.checked;
			}
			for(let item of this.productList) {
				if(item.productId !== found.productId) {
					item.checked = false;
				}
			}
		},
		change(e) {
			console.log("onchange", e);
		},
		tabClick(item) {
			console.log('item', item);
			if (item.name == '全已领料') {
				this.selectedIndex = 1;
			} else if (item.name == '等待领料') {
				this.selectedIndex = 0;
			}
			this.resetParams();
			this.queryPickingList();
		},
		
		advanceClick(item) {
			console.log(item);
			uni.$u.sleep().then(() => {
				this.show = !this.show
			});
			this.groupedProductList = this.groupedProducts();
		},
		selectCard(work) {
			console.log("work=", work);
			for (let item of this.orderList) {
				if (work.index != item.index) {
					item.selectedCard = 0;
				}
			}
			if (work.selectedCard === 1) {
				work.selectedCard = 0;
			} else {
				work.selectedCard = 1;
			}
		},
		floatOnclick(e) {
			// TODO 扫描按钮事件
			console.log("扫描按钮事件:", e);
			// alert("正在打开飞书摄像头扫码");
			let _this = this;
			window.h5sdk.ready(() => {
				tt.scanCode({
					scanType: ["barCode", "qrCode", "datamatrix", "pdf417"],
					barCodeInput: true,
					success(res) {
						console.log("扫描返回:", res);
						// alert("成功:"+JSON.stringify(res));
						_this.queryKey = res.result;
						_this.queryPickingList(false);
					},
					fail(res) {
						console.log(`scanCode fail:`, res);
						alert("失败:"+JSON.stringify(res));
					},
				});
			});
		},
		toDetail(order) {
			const contractCode = encodeURIComponent(order.contractCode);
			const orderCode = encodeURIComponent(order.orderCode);
			// PICK_DETAIL
			this.navigateTo(`/pages/work/order/pickingDetail?factoryId=${order.factoryId}&teamId=${order.teamId}&contractCode=${contractCode}&orderCode=${orderCode}&action=PICK_DETAIL&orderType=${this.orderType}&status=FINISHED`);
		},
		toPicking(order) {
			const contractCode = encodeURIComponent(order.contractCode);
			const orderCode = encodeURIComponent(order.orderCode);
			this.navigateTo(`/pages/work/order/pickingDetail?factoryId=${order.factoryId}&teamId=${order.teamId}&contractCode=${contractCode}&orderCode=${orderCode}&action=PICK_NUM&orderType=${this.orderType}&status=UNFINISHED`);
		},
		toFeedMtrl(order) {
			const contractCode = encodeURIComponent(order.contractCode);
			const orderCode = encodeURIComponent(order.orderCode);
			this.navigateTo(`/pages/work/order/feedMtrlDetail?factoryId=${order.factoryId}&teamId=${order.teamId}&contractCode=${contractCode}&orderCode=${orderCode}&orderType=${this.orderType}&status=UNFINISHED`);
		},
		toReturnMtrl(order) {
			const contractCode = encodeURIComponent(order.contractCode);
			const orderCode = encodeURIComponent(order.orderCode);
			this.navigateTo(`/pages/work/order/returnMtrlDetail?factoryId=${order.factoryId}&teamId=${order.teamId}&contractCode=${contractCode}&orderCode=${orderCode}&orderType=${this.orderType}&status=UNFINISHED`);
		},
		open() {
			// console.log('open');
			document.body.style.overflow = 'hidden'; // 禁用背景页面滚动
		},
		productConfirm() {
			const product = this.productList.find(item => item.checked);
			if (product) {
				this.productName = product.productName;
				this.queryPickingByQueryKey();
			} else {
				this.queryPickingByQueryKey();
			}
			this.close();
		},
		close() {
			this.show = false
			// console.log('close');
			document.body.style.overflow = ''; // 恢复背景页面滚动
		},
		reset() {
			for(let item of this.productList) {
				item.checked = false;
			}
			this.productName = null;
		},
		navigateTo (url) {
		  uni.navigateTo({ url: url })
		},
		textConvert(label, value) {
			return `${label}: ${value}`;
		},
		textConvertOfObj(label, work) {
			if (work.partHasPickingNum > 0 && work.partHasPickingNum != work.sumHasPickingNum) {
				return `${label}: 部分`;
			}
			return `${label}: ${work.sumHasPickingNum}`;
		},
	}
}
</script>

<style lang="scss" scoped>
.card-container{
	width: 100%;
	min-height: 100%;
	box-sizing: border-box;
	padding: 16rpx;
	background-color: #ECECEC;
}
.card-wrap{
	padding: 12rpx;
	border-radius: 12rpx;
	margin-bottom: 12rpx;
	background-color: #FFF;
	border: 1px solid #ddd; /* 默认边框 */
	transition: background-color 0.3s, border-color 0.3s;
	.card-item{
		display: flex;
		align-items: center;
		font-size: 28rpx;
		padding-left: 6rpx;
		padding-bottom: 18rpx;
		color: #40485d;
	}
	.card-item-txt{
		flex:1;
		overflow: hidden;
		text-overflow: ellipsis;
		white-space: nowrap;
	}
}
.card-btns{
	display: flex;
	justify-content: space-between;
	align-items: center;
}
.card-btns uni-button {
  flex: 1;
  margin: 0 5px; /* 调整按钮间距 */
}
.card-wrap-selected {
  border-color: #007bff; /* 选中状态的边框颜色 */
  background-color: #e7f0ff; /* 选中状态的背景颜色 */
}

.demo-layout {
	height: 25px;
	border-radius: 4px;
}
.bg-purple {
	background: #CED7E1;
}
.bg-purple-light {
	background: #e5e9f2;
}
</style>
